import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';

import { addTab } from '@/utils/utils';
import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Button,
  Card,
  Row,
  Col,
  Input,
  Table,
  Popconfirm,
  Divider,
} from 'antd';

import SaveArea from './components/SaveArea';

import '@ant-design/compatible/assets/index.css';

const { pathname } = window.location;

interface AreaInfoProps extends FormComponentProps {
  dispatch: Dispatch<any>;
  checkPerm: any;
  areaList: any;
  location: { query: any };
  screen: string;
}

interface AreaInfoState {
  searchValues: any;
  pageIndex: number;
  pageSize: number;
  saveVisible: boolean;
  rowId: number;
  recordArea:any;
}

@connect(
  ({
    campusCommunityArea: { areaList },
    common: { checkPerm },
    global: { screen },
  }: any) => ({
    areaList,
    checkPerm,
    screen,
  }),
)
class AreaInfoElem extends Component<AreaInfoProps, AreaInfoState> {
  columns = [
    {
      title: '序号',
      dataIndex: 'serialNo',
      width: 100,
    },
    {
      title: '区域名称',
      dataIndex: 'name',
      render: (text: string, record: any) => text,
    },
    {
      title: '显示',
      dataIndex: 'valid',
      width: 100,
      render: (text: number, record: any) => (text === 1 ? '是' : '否'),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
    },
    {
      title: '创建人',
      dataIndex: 'createUserName',
    },
    {
      title: '操作',
      dataIndex: 'id',
      width: 150,
      render: (id: number, record:any) => {
        const { checkPerm } = this.props;
        return (
          <Fragment>
            <span
              className={!checkPerm.update ? 'operLinkDisabled' : 'operLink'}
              onClick={() => this.handleEdit(record)}
            >
              编辑
            </span>
            <Divider type="vertical" />
            {checkPerm.operOther && (
              <Popconfirm
                title="确定要删除当前区域吗？"
                onConfirm={() => this.handleConfirm(id)}
                className="operLink"
                okText="确定"
                cancelText="取消"
              >
                删除
              </Popconfirm>
            )}
          </Fragment>
        );
      },
    },
  ];

  state: AreaInfoState = {
    searchValues: {},
    pageIndex: 1,
    pageSize: 20,
    saveVisible: false,
    rowId: 0,
    recordArea: {},
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...searchValues } = query;
    return {
      searchValues,
      pageIndex: Number(pageIndex) || 1,
      pageSize: Number(pageSize) || (nextProps.screen === 'sm' ? 100 : 20),
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.verifyPermissions();

    const { areaList } = this.props;
    if (areaList?.list?.length) return;

    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues, pageIndex, pageSize }: any = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)
      || pageIndex !== prevState.pageIndex
      || pageSize !== prevState.pageSize
      || searchValues.gardenId !== prevState.searchValues.gardenId
    ) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const { searchValues: { gardenName, name } } = this.state;
    const { form: { setFieldsValue } } = this.props;
    setFieldsValue({ gardenName, name });
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues, pageIndex, pageSize } = this.state;
    const params = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    return params;
  };

  verifyPermissions = () => {
    const addparams = {
      name: 'add',
      oper: 'add',
      resource: 'conf:conf_garden',
    };
    this.fetchAction('common/fetchCheckPerm', addparams);

    const updateparams = {
      name: 'update',
      oper: 'update',
      resource: 'conf:conf_garden',
    };
    this.fetchAction('common/fetchCheckPerm', updateparams);

    const otherparams = {
      name: 'operOther',
      oper: 'delete',
      resource: 'conf:conf_garden',
    };
    this.fetchAction('common/fetchCheckPerm', otherparams);
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();

    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { searchValues }: any = this.state;
      const query = { ...searchValues, ...values };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: `区域${searchValues.gardenName}`,
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { searchValues: { gardenName, gardenId } } = this.state;
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `区域${gardenName}`,
      url: `${pathname}?gardenId=${gardenId}`,
      isTopMenu: true,
    });
  };

  // 添加区域
  handleSave = (saveVisible: boolean) => {
    this.setState({ saveVisible, recordArea: {} });
  }

  // 编辑区域
  handleEdit = (recordArea:any) => this.setState({ saveVisible: true, recordArea });

  handleConfirm = (id: number) => {
    const { searchValues: fetchValues } = this.state;
    const params = { id, fetchValues };
    this.fetchAction('deleteArea', params);
  };

  onSelectChange = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = {
      ...searchValues,
      pageIndex,
      pageSize,
    };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: `区域${searchValues.gardenName}`,
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, payload = {}) => {
    if (typeName === 'saveArea') {
      const { form: { resetFields } } = this.props;
      resetFields(['name']);

      const { searchValues: { gardenId: id } } = this.state;
      const searchValues = {
        gardenId: id,
        name: '',
        pageIndex: 1,
        pageSize: 20,
      };
      this.setState({ searchValues });

      const { location: { query: { gardenId } } } = this.props;
      payload = {
        saveValues: { ...payload, gardenId },
        fetchValues: searchValues,
      };
    }

    const type = typeName.indexOf('common') >= 0
      ? typeName : `campusCommunityArea/${typeName}`;

    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  onClickRow = ({ id }: any) => ({
    onClick: () => {
      this.setState({ rowId: id });
    },
  })

  setRowClassName = ({ id }: any) => {
    const { rowId } = this.state;
    return id === rowId ? 'clickRowStyl' : '';
  }

  render() {
    const {
      pageIndex,
      pageSize,
      saveVisible,
      recordArea,
      searchValues,
    } = this.state;
    const {
      areaList,
      checkPerm,
      form: { getFieldDecorator },
      location: { query: { name: gardenName } },
    } = this.props;

    const dataSource = areaList ? areaList.list : [];
    const pagination: object = areaList
      ? {
        total: areaList.count,
        current: pageIndex,
        pageSize,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50', '100'],
        showTotal: () => `共${areaList.count || 0}条数据`,
        onChange: this.onSelectChange,
        onShowSizeChange: this.onSelectChange,
      }
      : {};

    return (
      <Fragment>
        <PageHeader />

        <Card className="searchForm" bordered={false}>
          <Form className="tableListForm" onSubmit={this.handleSearch}>
            <Row gutter={12}>
              <Col md={6} sm={24}>
                <Form.Item label="校园小区" colon={false}>
                  {getFieldDecorator('gardenName', { initialValue: gardenName })(
                    <Input disabled />,
                  )}
                </Form.Item>
              </Col>
              <Col md={6} sm={24}>
                <Form.Item label="区域名称" colon={false}>
                  {getFieldDecorator('name')(
                    <Input allowClear placeholder="请输入" />,
                  )}
                </Form.Item>
              </Col>
              <Col md={12} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    type="primary"
                    className="addButton smallButton marginL16"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false} className="tableList">
          {checkPerm.add && (
            <div className="tableBtns">
              <Button
                type="primary"
                size="small"
                className="smallButton"
                onClick={this.handleSave.bind(this, true)}
              >
                添加区域
              </Button>
            </div>
          )}
          <Table
            rowKey="id"
            tableLayout="fixed"
            className="statementTable tableHeight60"
            dataSource={dataSource}
            columns={this.columns}
            pagination={pagination}
            scroll={{ x: 600 }}
            onRow={this.onClickRow}
            rowClassName={this.setRowClassName}
          />
        </Card>

        <SaveArea
          saveVisible={saveVisible}
          recordArea={recordArea}
          searchValues={searchValues}
          handleCancel={this.handleSave.bind(this)}
          fetchAction={this.fetchAction.bind(this)}
        />
      </Fragment>
    );
  }
}

export default Form.create<AreaInfoProps>()(AreaInfoElem);
